<template>
	<view class="form">
		<u-tabs @change="tabChange" :list="typeList" lineWidth="60" lineColor="rgb(118, 118, 238)" :activeStyle="{
	            color: 'rgb(118, 118, 238)',
	             fontWeight: 'bold',
	             transform: 'scale(1.05)',
	         }" :inactiveStyle="{
	           color:'rgb(102, 102, 102)',
	 		  transform: 'scale(1)'
	 			
	         }" itemStyle="{padding-left: 15px; padding-right: 10px; height: 40px; flex: 1;}">
		</u-tabs>
		<u-line color="rgb(229, 230, 235)"></u-line>
		<u--form labelPosition="left" :model="orderModel" ref="orderForm" labelWidth="80">
			<u-form-item prop="propertyPicture" label="物品图片">

				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="1" :previewFullImage="true"></u-upload>
			</u-form-item>

			<u-form-item prop="describe" :label="currentOrderType!==0?  '丢失物品':'拾到物品'" borderBottom>
				<u--input v-model="orderModel.describe" placeholder="请描述物品信息" border="none"></u--input>
			</u-form-item>
			<u-form-item prop="lostOrFindTime" :label="currentOrderType!==0?  '丢失时间':'拾物时间'" borderBottom
				@click="showRequireTime = true; hideKeyboard()">
				<u--input v-model="orderModel.lostOrFindTime" :placeholder="currentOrderType!==0?  '请输入丢失时间':'请输入拾物时间'"
					border="none" disabled disabledColor="#ffffff"></u--input>
				<u-icon slot="right" name="arrow-right" class="arrow"></u-icon>
			</u-form-item>
			<!-- 丢失地点 -->
			<u-form-item label="丢失地点" prop="lostOrFindAddress" borderBottom v-if="currentOrderType!==0">
				<u--input v-model="orderModel.lostOrFindAddress" :placeholder="sourcePlaceHolder" border="none">
				</u--input>
			</u-form-item>
			<!-- 捡到物品地点 -->
			<u-form-item label="拾物地点" prop="lostOrFindAddress" borderBottom v-else>
				<u--input v-model="orderModel.lostOrFindAddress" :placeholder="sourcePlaceHolder" border="none">
				</u--input>
			</u-form-item>
			<!-- 联系地址 -->
			<u-form-item prop="targetAddress" label="联系地址" borderBottom>
				<u--input v-model="orderModel.targetAddress" :placeholder="targetPlaceHolder" border="none">
				</u--input>
			</u-form-item>
			<!-- 联系方式-->
			<!-- <u-form-item prop="phone" label="联系方式" borderBottom>
				<u--input v-model="orderModel.phone" placeholder="请输入联系方式" border="none"></u--input>
			</u-form-item> -->
			<u-form-item prop="remark" label="备注" borderBottom>
				<u--input v-model="orderModel.remark" placeholder="可详细描述下物品信息,比如品牌" border="none"></u--input>
			</u-form-item>
		</u--form>
		<u-datetime-picker :show="showRequireTime" :value="lostOrFindTime" mode="datetime" closeOnClickOverlay
			@confirm="requireTimeConfirm" @cancel="requireTimeClose"></u-datetime-picker>
		<view class="operation">
			<view class="button">
				<u-button text="立即发布" shape="circle" @click="submit"
					color="linear-gradient(135.00deg, rgba(118,118,238,1.00) 0.321%,rgba(138,138,238,1.00) 100%)">
				</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import { baseUrl } from '../../utils/baseConfig.js'
	export default {
		components: {},
		data() {
			return {
				//失物招领单类型：0：失物招领，1:寻物启事
				currentOrderType: 0,
				sourcePlaceHolder: '请输入物品丢失地点',
				targetPlaceHolder: '请填入领取物品的地点',
				showRequireTime: false,
				lostOrFindTime: Number(new Date()),
				typeList: [{
					name: '失物招领',
				}, {
					name: '寻物启事',
				}],
				fileList1: [], //图片列表
				orderModel: {
					lostOrFindTime: '',
					lostOrderType: 0,
					describe: '',
					remark: '',
					lostOrFindAddress: '',
					targetAddress: '',
					// phone: '',
					propertyPicture: ''
				},
				rules: {
					'propertyPicture': {
						type: 'string',
						required: true,
						message: '请上传物品图片',
						trigger: ['change']
					},
					'describe': {
						type: 'string',
						required: true,
						message: '请描述物品信息',
						trigger: ['change']
					},
					'lostOrFindTime': {
						type: 'string',
						required: true,
						message: '请输入时间',
						trigger: ['change']
					},
					'lostOrFindAddress': {
						type: 'string',
						required: true,
						message: '请输入地址',
						trigger: ['change']
					},
					'targetAddress': {
						type: 'string',
						required: true,
						message: '请输入联系地址',
						trigger: ['change'],
					},
					// 'phone': {
					// 	type: 'string',
					// 	required: true,
					// 	message: '请输入联系方式',
					// 	trigger: ['change']
					// },

					'remark': {
						type: 'string',
						required: true,
						message: '请输入备注',
						trigger: ['change']
					},
				}
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.orderForm.setRules(this.rules)
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					if (event.name === '1') {
						this.orderModel.propertyPicture = result
						this.$refs.orderForm.validateField('propertyPicture')
					}
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))


					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}api/private/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						header: {
							"Authorization": this.$store.getters.userInfo && this.$store.getters.userInfo
								.token ? this.$store
								.getters.userInfo.token : ''
						},
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							const url = JSON.parse(res.data).data.url
							resolve(url)
						}
					});
				})
			},
			tabChange(e) {
				this.currentOrderType = e.index
				switch (this.currentOrderType) {
					case 0:
						this.sourcePlaceHolder = '拾物地点'
						this.targetPlaceHolder = '领取地点'
						break;
					case 1:
						this.sourcePlaceHolder = '丢失地点'
						this.targetPlaceHolder = '归还地点'
						break
				}

			},
			requireTimeClose() {
				this.showRequireTime = false
			},
			requireTimeConfirm(e) {
				this.showRequireTime = false
				this.orderModel.lostOrFindTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
			},
			submit() {
				const userInfo = this.$store?.getters?.userInfo?.userInfoDetail || null
				console.log('用户信息', userInfo)
				console.log('model', this.orderModel)
				this.$refs.orderForm.validate().then(res => {
					const data = {
						"uid": userInfo.uid,
						...this.orderModel,
						"lostOrderType": String(this.currentOrderType),
						"phone": this.$store?.getters?.userInfo?.userPhone
					}
					this.$http('post', 'api/private/lostAndFind/create', {
						data,
						success: (res) => {
							setTimeout(() => {
								let pages = getCurrentPages(); // 当前页面
								let beforePage = pages[pages.length - 2];
								uni.navigateBack({
									delta: 1,
									success: () => {
										console.log(beforePage.route)
										beforePage.$vm.getLostOrder()
									}
								})
							}, 1000)
						},
						successMsg: this.currentOrderType == 0 ? '发布失物招领成功！' : '发布寻物启事成功'
					})
				}).catch(errors => {
					uni.$u.toast('请将信息填写完整！')
				})
			},

			hideKeyboard() {
				uni.hideKeyboard()
			}
		},
	}

</script>


<style scoped lang="scss">
	::v-deep .u-tabs .u-tabs__wrapper__nav__item {
		flex: 1;

	}

	::v-deep .u-tabs__wrapper__nav__item__text {
		font-size: 14px;
	}

	::v-deep .u-form-item__body__right__content__slot {
		justify-content: end;
	}

	::v-deep .u-number-box__plus {
		background-color: rgb(163, 181, 250) !important;
	}


	::v-deep .u-textarea {
		background: rgb(242, 242, 242);
		border-radius: 8px;
	}

	.form {
		height: 100vh;
		background: #fff;
		padding: 0 15px;

	}

	.order-container {
		padding: 15px;

		.icon {
			width: 24px;
			height: 24px;
			margin-right: 10px;
		}

		.arrow {
			margin-left: 10px;
		}


	}

	.operation {
		margin-top: 50px;
		padding: 0 15px;
	}

	.button {
		width: calc(100% - 30px);
	}

</style>

